# Create your views here
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User
from accounts.models import UserProfile
from random import randint
from mailaux import sendEmail
from django import forms
from django.forms import ValidationError

def generateCode():
    sz = 50
    s = ""
    for i in xrange(50):
        s += chr(65+randint(0,25))
    return s

def register(request):
    post = request.POST
    try:
        f = forms.CharField()
        username = f.clean(post["username"])
        password = f.clean(post["password"])
        f = forms.EmailField()
        email = f.clean(post["email"])
    except:
        return render_to_response('registration/register.html',{'erro':'Please fill all fiedls correctly',},context_instance=RequestContext(request))

    ele = User.objects.filter(username=username)

    if len(ele):
        return render_to_response('registration/register.html',{"erro":"UserName already exists"},context_instance=RequestContext(request))

    user = User.objects.create_user(username,email,password)
    user.is_active = False
    user.save()
        
    profile = UserProfile()
    profile.user = user
    profile.confirmationCode = generateCode()
    print profile.confirmationCode
    sendEmail(email,"Congratulations for Registering in Dmail System","http://localhost:8000/accounts/confirm\n\n" +profile.confirmationCode)
    profile.save()
    user.save()

    return render_to_response('registration/confirm.html',context_instance=RequestContext(request))

def askConfirmationCode(request):
    post = request.POST
    if "username" in post and "code" in post:
        try:
            user = User.objects.get(username=post['username'])
            if user.get_profile().confirmationCode == post['code']:
                user.is_active = True
                user.save()
                return HttpResponseRedirect('login')
        except:
            pass

    return render_to_response('registration/confirm.html',context_instance=RequestContext(request))

